package com.playcrab.adouban;

import com.google.gdata.client.douban.DoubanService;
import com.playcrab.adouban.util.Constants;
import com.playcrab.adouban.util.DoubanAPI;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
 

/**
 * @author kevinye
 */
public class Auth extends BaseActivity {
	private static final String LOG_TAG = "Auth";

	private static final int MENU_EXIT = Menu.FIRST + 12;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(getString(R.string.login));
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		
		setContentView(R.layout.auth); 
		Button authButton = (Button) findViewById(R.id.auth_login_button); 
		authButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				 openWebBrowser(Auth.this.getRequestUrl() );
				 finish();
			}
		});
		
		//openWebBrowser(getRequestUrl());
	}

	private String getRequestUrl() {

		DoubanService myService = DoubanAPI.getInstance().getService();
		
		String url = myService.getAuthorizationUrl(Constants.OAUTH_CALLBACK);
		Log.i(LOG_TAG, "url=" + url);

		SharedPreferences settings = getSharedPreferences(
				Constants.PREF_DOUBAN, 0);
		settings.edit().putString(Constants.OAUH_TOKEN,
				myService.getRequestToken()).putString(
						Constants.OAUTH_TOKEN_SECRET,
				myService.getRequestTokenSecret()).commit();

		return url;
	}

	protected void openWebBrowser(String url) {
		Log
				.i(this.getClass().getName(), "about to launch browser, url: "
						+ url);
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(url));
		startActivity(i);
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
	            case MENU_EXIT: {
	               finish(); 
	                return true;
	            }
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		
		menu.add(0, MENU_EXIT, 0, "退出").setIcon(android.R.drawable.ic_delete)
		.setAlphabeticShortcut('X'); 
		return true;
	}
}